/*
Developed by @jsong v10.0.20180312
https://mp.weixin.qq.com/debug/wxadoc/dev/
*/
var config = require('config.js');
module.exports = {
	//配置参数
	config: config,
	log: console.log,
	//GET网络请求
	get: function (url, data, callback) {
		var helper = this, person = this.storage('person'),
			success = null,
			fail = null,
			complete = null;
		if (!/^http/.test(url)) {
			if (config.apiUrl.substr(-1, 1) != '/' && url.substr(0, 1) != '/') url = '/' + url;
			url = config.apiUrl + url;
			url += (url.indexOf('?') > -1 ? '&' : '?') + 'is_mini=1';
			if (url.indexOf('sign=') == -1 && person && person.sign) {
				url += (url.indexOf('?') > -1 ? '&' : '?') + 'sign=' + person.sign;
			}
		}
		if (this.isFunction(data)) {
			success = data;
			data = null;
		} else if (this.isJson(data) && !this.isFunction(callback) && !this.isJson(callback)) {
			if (this.isFunction(data.success)) success = data.success;
			if (this.isFunction(data.fail)) fail = data.fail;
			if (this.isFunction(data.complete)) complete = data.complete;
			data = null;
		} else if (this.isFunction(callback)) {
			success = callback;
		} else if (this.isJson(callback)) {
			if (this.isFunction(callback.success)) success = callback.success;
			if (this.isFunction(callback.fail)) fail = callback.fail;
			if (this.isFunction(callback.complete)) complete = callback.complete;
		}
		var requestTask = wx.request({
			url: url,
			method: 'GET',
			data: data,
			dataType: 'STRING',
			header: { 'content-type': 'application/x-www-form-urlencoded' },
			success: function (res) {
				helper.overload(false);
				var json = res.data.trim();
				try {
					json = JSON.parse(json);
					if (typeof json.error != 'undefined' && json.error != 0) {
						if (typeof json.msg != 'undefined') {
							setTimeout(function () {
								helper.overloadError(json.msg);
							}, 300);
						}
						if (helper.isFunction(fail)) fail();
						return;
					}
					if (helper.isFunction(success)) success(json);
				} catch (e) {
					console.log(e);
					console.log(url);
					console.log(res.data);
					if (helper.isFunction(fail)) fail();
				}
			},
			fail: function (res) {
				console.log(res);
				if (helper.isFunction(fail)) {
					fail();
				} else {
					$.overloadError('数据错误');
				}
			}
		});
		return requestTask;
		//requestTask.abort();//取消请求任务
	},
	//POST网络请求
	post: function (url, data, callback) {
		var helper = this, person = this.storage('person'),
			success = null,
			fail = null,
			complete = null;
		if (!/^http/.test(url)) {
			if (config.apiUrl.substr(-1, 1) != '/' && url.substr(0, 1) != '/') url = '/' + url;
			url = config.apiUrl + url;
			url += (url.indexOf('?') > -1 ? '&' : '?') + 'is_mini=1';
			if (url.indexOf('sign=') == -1 && person && person.sign) {
				url += (url.indexOf('?') > -1 ? '&' : '?') + 'sign=' + person.sign;
			}
		}
		if (this.isFunction(callback)) {
			success = callback;
		} else if (this.isJson(callback)) {
			if (this.isFunction(callback.success)) success = callback.success;
			if (this.isFunction(callback.fail)) fail = callback.fail;
			if (this.isFunction(callback.complete)) complete = callback.complete;
		}
		var requestTask = wx.request({
			url: url,
			method: 'POST',
			data: data,
			dataType: 'STRING',
			header: { 'content-type': 'application/x-www-form-urlencoded' },
			success: function (res) {
				helper.overload(false);
				var json = res.data.trim();
				try {
					json = JSON.parse(json);
					if (typeof json.error != 'undefined' && json.error != 0) {
						if (typeof json.msg != 'undefined') {
							setTimeout(function () {
								helper.overloadError(json.msg);
							}, 300);
						}
						if (helper.isFunction(fail)) fail();
						return;
					}
					if (helper.isFunction(success)) success(json);
				} catch (e) {
					console.log(e);
					console.log(url);
					console.log(res.data);
					if (helper.isFunction(fail)) fail();
				}
			},
			fail: function (res) {
				console.log(res);
				if (helper.isFunction(fail)) {
					fail();
				} else {
					$.overloadError('数据错误');
				}
			}
		});
		return requestTask;
	},
	//UPLOAD网络请求
	upload: function (url, options, callback, progress) {
		if (!this.isJson(options) || typeof (options.path) == 'undefined') {
			this.overloadError('缺少要上传文件资源的路径');
			return;
		}
		var helper = this, person = this.storage('person');
		if (!/^http/.test(url)) {
			if (config.apiUrl.substr(-1, 1) != '/' && url.substr(0, 1) != '/') url = '/' + url;
			url = config.apiUrl + url;
			url += (url.indexOf('?') > -1 ? '&' : '?') + 'is_mini=1';
			if (url.indexOf('sign=') == -1 && person && person.sign) {
				url += (url.indexOf('?') > -1 ? '&' : '?') + 'sign=' + person.sign;
			}
		}
		var task = wx.uploadFile({
			url: url,
			filePath: options.path,
			name: typeof (options.name) != 'undefined' ? options.name : 'filename',
			formData: typeof (options.data) != 'undefined' ? options.data : null,
			dataType: 'STRING',
			success: function (res) {
				helper.overload(false);
				var json = res.data.trim();
				try {
					json = JSON.parse(json);
					if (typeof json.error != 'undefined' && json.error != 0) {
						helper.overloadError(json.msg);
						return;
					}
					if (helper.isFunction(callback)) callback(json);
				} catch (e) {
					console.log(e);
					console.log(url);
					console.log(res.data);
				}
			},
			fail: function (res) {
				console.log(res);
				helper.overloadError('数据错误');
			}
		});
		return task;
		if (this.isFunction(progress)) {
			task.onProgressUpdate(function (res) {
				progress(res);
				//res.progress//进度百分比
				//res.totalBytesSent//已上传的数据长度,单位Bytes
				//res.totalBytesExpectedToSend//预期需要上传的数据总长度,单位Bytes
			});
		}
		//task.abort();// 中断任务
	},
	//DOWNLOAD网络请求
	download: function (url, saveFile, callback, progress) {
		var helper = this, person = this.storage('person');
		this.overload();
		if (!/^http/.test(url)) {
			if (config.apiUrl.substr(-1, 1) != '/' && url.substr(0, 1) != '/') url = '/' + url;
			url = config.apiUrl + url;
			url += (url.indexOf('?') > -1 ? '&' : '?') + 'is_mini=1';
			if (url.indexOf('sign=') == -1 && person && person.sign) {
				url += (url.indexOf('?') > -1 ? '&' : '?') + 'sign=' + person.sign;
			}
		}
		if (this.isFunction(saveFile)) {
			progress = callback;
			callback = saveFile;
			saveFile = false;
		}
		var task = wx.downloadFile({
			url: url,
			success: function (res) {
				helper.overload(false);
				if (res.statusCode === 200) {
					if (saveFile) {
						wx.saveFile({
							tempFilePath: res.tempFilePath,
							success: function (res) {
								var savedFilePath = res.savedFilePath;
								if (helper.isFunction(callback)) callback(savedFilePath);
							}
						});
					} else {
						if (helper.isFunction(callback)) callback(res.tempFilePath);
					}
				}
			}
		});
		return task;
		if (this.isFunction(progress)) {
			task.onProgressUpdate(function (res) {
				progress(res);
				//res.progress//进度百分比
				//res.totalBytesWritten//已下载的数据长度,单位Bytes
				//res.totalBytesExpectedToWrite//预期需要下载的数据总长度,单位Bytes
			});
		}
		//task.abort();// 中断任务
	},
	//是否数组
	isArray: function (obj) {
		return (obj instanceof Array);
	},
	//是否函数
	isFunction: function (func) {
		return (func instanceof Function);
	},
	//是否JSON对象
	isJson: function (obj) {
		if (obj && typeof (obj) == 'object' &&
			Object.prototype.toString.call(obj).toLowerCase() == '[object object]' &&
			!obj.length) return true;
		return false;
	},
	//是否数字
	isNumber: function (str) {
		return !isNaN(str);
	},
	//是否中文
	isCN: function (str) {
		return /^[\u4e00-\u9fa5]+$/.test(str);
	},
	//是否固话
	isTel: function (str) {
		return /^((\d{3,4}-)?\d{8}(-\d+)?|(\(\d{3,4}\))?\d{8}(-\d+)?)$/.test(str);
	},
	//是否手机
	isMobile: function (str) {
		return /^(\+?86)?1[3-8]\d{9}$/.test(str);
	},
	//是否邮箱
	isEmail: function (str) {
		return /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(str);
	},
	//是否日期字符串
	isDate: function (str) {
		return /^(?:(?!0000)[0-9]{4}[\/-](?:(?:0?[1-9]|1[0-2])[\/-](?:0?[1-9]|1[0-9]|2[0-8])|(?:0?[13-9]|1[0-2])[\/-](?:29|30)|(?:0?[13578]|1[02])[\/-]31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)[\/-]0?2[\/-]29)$/.test(str);
	},
	//是否身份证(严格)
	isIdCard: function (str) {
		var Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1], //加权因子
			ValideCode = [1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2]; //身份证验证位值,10代表X
		function idCardValidate(idCard) {
			if (idCard.length == 15) {
				return is15IdCard(idCard); //进行15位身份证的验证
			} else if (idCard.length == 18) {
				return is18IdCard(idCard) && isTrue18IdCard(idCard.split('')); //进行18位身份证的基本验证和第18位的验证
			} else {
				return false;
			}
		}
		function isTrue18IdCard(idCard) {
			var sum = 0;
			if (idCard[17].toLowerCase() == 'x') idCard[17] = 10; //将最后位为x的验证码替换为10方便后续操作
			for (var i = 0; i < 17; i++) sum += Wi[i] * idCard[i]; //加权求和
			var valCodePosition = sum % 11; //得到验证码所位置
			if (idCard[17] == ValideCode[valCodePosition]) {
				return true;
			} else {
				return false;
			}
		}
		function is18IdCard(idCard) {
			var year = idCard.substring(6, 10),
				month = idCard.substring(10, 12),
				day = idCard.substring(12, 14),
				date = new Date(year, parseInt(month) - 1, parseInt(day));
			if (date.getFullYear() != parseInt(year) || date.getMonth() != parseInt(month) - 1 || date.getDate() != parseInt(day)) {
				return false;
			} else {
				return true;
			}
		}
		function is15IdCard(idCard) {
			var year = idCard.substring(6, 8),
				month = idCard.substring(8, 10),
				day = idCard.substring(10, 12),
				date = new Date(year, parseInt(month) - 1, parseInt(day));
			if (date.getYear() != parseInt(year) || date.getMonth() != parseInt(month) - 1 || date.getDate() != parseInt(day)) {
				return false;
			} else {
				return true;
			}
		}
		return idCardValidate(str);
	},
	//JSON字符串转JSON对象
	jsonObj: function (str) {
		return JSON.parse(str);
	},
	//JSON对象转JSON字符串
	jsonString: function (obj) {
		return JSON.stringify(obj);
	},
	//使用对象扩展另一个对象
	extend: function () {
		for (var i = arguments.length; i > 0; i--) {
			for (var k in arguments[i]) {
				arguments[i - 1][k] = arguments[i][k];
			}
		}
		return arguments[0];
	},
	//设置当前页面标题
	setTitle: function (title) {
		wx.setNavigationBarTitle({
			title: title
		});
	},
	//获取当前页面路由列表
	getApps: function () {
		return getCurrentPages();
	},
	//获取当前页面
	getPage: function () {
		var pages = getCurrentPages(), page = pages[pages.length - 1];
		page.path = page.route;
		return page;
	},
	//设置本地存储
	storage: function (key, data) {
		if (typeof (data) == 'undefined' || data === null) {
			try {
				var value = wx.getStorageSync(key);
				if (value) {
					return value;
				}
				return null;
			} catch (e) {
				return null;
			}
		} else if (data === false) {
			try {
				wx.removeStorageSync(key);
			} catch (e) { }
		} else {
			wx.setStorageSync(key, data);
			try {
				wx.setStorageSync(key, data);
			} catch (e) { }
		}
	},
	//清除本地存储
	clearStorage: function () {
		try {
			wx.clearStorageSync()
		} catch (e) { }
	},
	//获取当前地理位置
	getLocation: function (callback, type) {
		if (!this.isFunction(callback)) return;
		if (typeof (type) == 'undefined') type = 'wgs84';
		wx.getLocation({
			type: type,//wgs84返回gps坐标，gcj02返回可用于wx.openLocation的坐标
			success: function (res) {
				callback(res);
				/*
				latitude 纬度，浮点数，范围为 - 90~90，负数表示南纬
				longitude 经度，浮点数，范围为 - 180~180，负数表示西经
				speed 速度，浮点数，单位m/s
				accuracy 位置的精确度
				altitude 高度，单位m
				verticalAccuracy 垂直精度，单位m（Android 无法获取，返回0）
				horizontalAccuracy 水平精度，单位 m
				*/
			}
		});
	},
	//打开地图选择位置
	chooseAddress: function (callback) {
		if (!this.isFunction(callback)) return;
		wx.chooseAddress({
			success: function (res) {
				callback(res);
				/*
				name 位置名称
				address 详细地址
				latitude 纬度，浮点数，范围为 - 90~90，负数表示南纬
				longitude 经度，浮点数，范围为 - 180~180，负数表示西经
				*/
			}
		});
	},
	//调起微信内置地图查看位置, 需使用gcj02类型的经纬度
	openLocation: function (options) {
		wx.openLocation({
			latitude: options.latitude, //纬度，范围为 - 90~90，负数表示南纬
			longitude: options.longitude, //经度，范围为-180~180，负数表示西经
			scale: options.scale || 18, //缩放比例，范围5~18，默认为18
			name: options.name || '', //位置名
			address: options.address || '' //详细地址
		});
	},
	//调起拨打电话
	openCall: function (mobile) {
		wx.makePhoneCall({
			phoneNumber: mobile
		});
	},
	//调起扫描
	scan: function (options) {
		options = this.extend({
			camera: false,//是否只能从相机扫码，不允许从相册选择图片
			success: null,
			fail: null
		}, options);
		wx.scanCode({
			onlyFromCamera: options.camera,
			success: options.success,
			fail: options.fail
		});
		/*
		success返回参数
		result 所扫码的内容
		scanType 所扫码的类型
		charSet 所扫码的字符集
		path 当所扫的码为当前小程序的合法二维码时，会返回此字段，内容为二维码携带的path
		*/
	},
	//提示框
	overload: function (text, icon, delay) {
		var $ = this,
			apps = getCurrentPages();
		if (!apps || !this.isArray(apps) || !apps.length) return;
		var app = apps[apps.length - 1],
			overload = (app.data && app.data.overload) ? app.data.overload : {};
		if (typeof text == 'boolean' && !text) {
			if (overload.delay > 0) return;
			if (overload.timeout) clearTimeout(overload.timeout);
			var view = (overload.view && overload.view.length) ? overload.view : '';
			var timeout = setTimeout(function () {
				if (app.data.overload.timeout) clearTimeout(app.data.overload.timeout);
				app.setData({
					overload: $.extend(overload, {
						view: view + ' load-view-out'
					})
				});
				setTimeout(function () {
					app.setData({
						overload: $.extend(overload, {
							show: false,
							showDelay: false,
							view: ''
						})
					});
				}, 300);
			}, 10);
			app.setData({
				overload: $.extend(overload, {
					timeout: timeout
				})
			});
			return;
		}
		if (typeof text != 'string') text = '';
		if (typeof icon != 'string') icon = '';
		if (typeof delay != 'number') delay = 0;
		var showDelay = false;
		if (overload.timeout) clearTimeout(overload.timeout);
		app.setData({
			overload: $.extend(overload, {
				show: true,
				showDelay: showDelay,
				view: text.length ? '' : 'nontext',
				icon: icon,
				text: text,
				delay: delay,
				timeout: null
			})
		});
		setTimeout(function () {
			app.setData({
				overload: $.extend(app.data.overload, {
					view: app.data.overload.view + ' load-view-in'
				})
			});
			if (delay > 0) {
				var overload = app.data.overload;
				var timeout = setTimeout(function () {
					if (overload.timeout) clearTimeout(overload.timeout);
					var view = (overload.view && overload.view.length) ? overload.view : '';
					app.setData({
						overload: $.extend(overload, {
							view: view + ' load-view-out'
						})
					});
					setTimeout(function () {
						app.setData({
							overload: $.extend(overload, {
								show: false,
								showDelay: false,
								view: ''
							})
						});
					}, 300);
				}, delay);
				app.setData({
					overload: $.extend(overload, {
						timeout: timeout
					})
				});
			}
		}, 0);
	},
	overloadSuccess: function (text) {
		this.overload(text, 'load-success', 4000);
	},
	overloadError: function (text) {
		this.overload(text, 'load-error', 4000);
	},
	overloadWarning: function (text) {
		this.overload(text, 'load-warning', 4000);
	},
	alert: function (content) {
		var options = {
			content: content,
			showCancel: false
		};
		this.confirm(options);
	},
	confirm: function (options) {
		var helper = this;
		options = this.extend({
			title: '', //提示的标题
			content: '', //提示的内容
			okText: '确定', //确定按钮文字
			cancelText: '取消', //取消按钮文字
			okColor: '#3CC51F', //确定按钮文字颜色
			showCancel: true, //是否显示取消按钮
			success: null, //按下确定按钮后执行
			cancel: null //按下确定按钮后执行
		}, options);
		wx.showModal({
			title: options.title,
			content: options.content,
			confirmText: options.okText,
			cancelText: options.cancelText,
			confirmColor: options.okColor,
			showCancel: options.showCancel,
			success: function (res) {
				if (res.confirm) {
					if (helper.isFunction(options.success)) options.success();
				} else if (res.cancel) {
					if (helper.isFunction(options.cancel)) options.cancel();
				}
			}
		});
	},
	actionSheet: function (options) {
		var helper = this;
		options = this.extend({
			items: [], //按钮的文字数组，数组长度最大为6个
			color: '#000000', //按钮的文字颜色
			success: null, //按下按钮后执行
			fail: null //按下取消按钮后执行
		}, options);
		wx.showActionSheet({
			itemList: options.items,
			success: function (res) {
				if (helper.isFunction(options.success)) {
					options.success(res.tapIndex);
				}
			},
			fail: function () {
				if (helper.isFunction(options.fail)) options.fail();
			}
		});
	},
	//调起选择图片
	selectImage: function (success) {
		if (!this.isFunction(success)) return;
		wx.chooseImage({
			success: function (res) {
				//res.tempFiles[0].path
				//res.tempFiles[0].size
				var tempFilePaths = res.tempFilePaths;
				success(tempFilePaths[0]);
			}
		});
	},
	//调起支付
	payment: function (data, callback) {
		var helper = this;
		if (typeof (data) == 'string') data = this.jsonObj(data);
		wx.requestPayment({
			'timeStamp': data.timeStamp,
			'nonceStr': data.nonceStr,
			'package': data.package,
			'signType': 'MD5',
			'paySign': data.paySign,
			success: function (res) {
				if (res.errMsg == 'requestPayment:ok') {
					if (helper.isFunction(callback)) callback();
				}
				console.log(res);
			},
			fail: function (res) {
				console.log(res);
				console.log(data);
			}
		});
	},
	//配置一个动画
	animation: function (duration) {
		return wx.createAnimation({
			transformOrigin: '50% 50% 0',
			duration: duration,
			timingFunction: 'ease-out',
			delay: 0
		});
	},
	//JSON对象转网址参数
	paramUrl: function (obj) {
		return Object.keys(obj).map(function (k) {
			return encodeURIComponent(k) + '=' + encodeURIComponent(obj[k]);
		}).join('&');
	},
	//转完整网址
	wapUrl: function (url) {
		var person = this.storage('person');
		if (!/^http/.test(url)) {
			if (config.apiUrl.substr(-1, 1) != '/' && url.substr(0, 1) != '/') url = '/' + url;
			url = config.apiUrl + url;
			url += (url.indexOf('?') > -1 ? '&' : '?') + 'is_mini=1';
			if (url.indexOf('sign=') == -1 && person && person.sign) {
				url += (url.indexOf('?') > -1 ? '&' : '?') + 'sign=' + person.sign;
			}
		}
		return url;
	},
	//调起微信的收货地址
	getAddress: function (callback) {
		if (!this.isFunction(callback)) return;
		wx.chooseAddress({
			success: function (res) {
				//console.log(res.userName) //收货人姓名
				//console.log(res.postalCode) //邮编
				//console.log(res.provinceName) //国标收货地址第一级地址
				//console.log(res.cityName) //国标收货地址第二级地址
				//console.log(res.countyName) //国标收货地址第三级地址
				//console.log(res.detailInfo) //详细收货地址信息
				//console.log(res.nationalCode) //收货地址国家码
				//console.log(res.telNumber) //收货人手机号码
				callback({
					name: res.userName,
					zip: res.postalCode,
					province: res.provinceName,
					city: res.cityName,
					district: res.countyName,
					address: res.detailInfo,
					tel: res.telNumber
				});
			}
		});
	},
	//省市区地址自动组合
	comboCity: function (province, city, district, address, apart) {
		apart = typeof (apart) != 'undefined' ? apart : '';
		var html = province;
		if (typeof (city) != 'undefined' && province != city) html += apart + city;
		if (typeof (district) != 'undefined') html += apart + district;
		if (typeof (address) != 'undefined') html += apart + address;
		return html;
	}
}